package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
聊天室的客服端
 */
public class Client3 {
    private Socket socket;
    public Client3(){
        //初始化数据 localhost表示本机
        try {
            /*
            实例化Socket时就是与远程服务器建立连接的过程
            需要传递两个参数：
            1.服务器的ip地址，用于找到网络上对方的计算机
            2.服务端口，用于找到服务器计算机上的服务端口的应用程序
             */
            System.out.println("正在连接服务器...");
            socket = new Socket("localhost",9090);
            System.out.println("与服务器建立连接成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        Scanner sc= new Scanner(System.in);
        try {
            //发送
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            pw.println("你好服务器");

            //接收
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String temp ;


            //pw.flush();
            while (true) {
                System.out.println("输入发送的消息");
                String s = sc.nextLine();
                if ("1".equals(s)){
                    pw.println("GG" + "   "+"关闭");
                    break;
                }

                pw.println(s);
               // pw.flush();

                temp = br.readLine();
                System.out.println(temp);
            }
            /*while ((temp = br.readLine())!=null){

                System.out.println(temp);
            }*/
            pw.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client3 client = new Client3();
        client.start();
    }
}
